package net.ariel.myideablog.impl;

import java.util.Collection;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

import net.ariel.myideablog.dao.ICategory;
import net.ariel.myideablog.model.Category;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class CategoryImpl implements ICategory {

	private PersistenceManagerFactory persistenceManagerFactory;
	
	public void setPersistenceManagerFactory(PersistenceManagerFactory pmf) {
		this.persistenceManagerFactory = pmf;
	}
	
	@Override
	public List<Category> getAllCategories() {
		// TODO Auto-generated method stub
		PersistenceManager pm = persistenceManagerFactory.getPersistenceManager();
		String query = "select from " + Category.class.getName();
		return (List<Category>) pm.newQuery(query).execute();
	}

	@Override
	public List<Category> getCategoriesByPage(int offset, int limit) {
		PersistenceManager pm = persistenceManagerFactory.getPersistenceManager();
		String query = "select from "+Category.class.getName()+" range "+Integer.toString(offset)+" , "+Integer.toString(limit);
		return (List<Category>)pm.newQuery(query).execute();
	}
	@Override
	public void saveCategory(Category category) {
		// TODO Auto-generated method stub
		PersistenceManager pm = persistenceManagerFactory.getPersistenceManager();
		try {
			pm.makePersistent(category);
		}
		finally {
			pm.close();
		}
	}
	
	@SuppressWarnings("finally")
	@Override
	public Category getCategory(String categoryKey) {	
		Key key = KeyFactory.stringToKey(categoryKey);
		PersistenceManager pm = persistenceManagerFactory.getPersistenceManager();
		try {
			Category category = pm.getObjectById(Category.class, key);
			return category;
		}
		finally {
			pm.close();
		}
	}
	
	@Override
	public void updateCategory(String categoryKey, String categoryName) {
		PersistenceManager pm = persistenceManagerFactory.getPersistenceManager();
		try {
			Category category = pm.getObjectById(Category.class, KeyFactory.stringToKey(categoryKey));
			category.setName(categoryName);
		}
		finally {
			pm.close();
		}
	}
	
	@Override
	public void deleteCategory(String categoryKey) {
		Key key = KeyFactory.stringToKey(categoryKey);
		PersistenceManager pm = persistenceManagerFactory.getPersistenceManager();
		try {
			Category category = pm.getObjectById(Category.class, key);
			pm.deletePersistent(category);
		}
		finally {
			pm.close();
		}
	}
	
	@Override
	public int getCategoryNumber() {
		String query = "select count(this) from "+Category.class.getName();
		PersistenceManager pm = persistenceManagerFactory.getPersistenceManager();
		try {
			Integer number = (Integer)pm.newQuery(query).execute();
			return number.intValue();
		}
		finally {
			pm.close();
		}
	}

}
